package com.ms.architecture.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment

abstract class DataBindingFragment : Fragment() {

    protected var mActivity: AppCompatActivity? = null
    protected var mBinding: ViewDataBinding? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        this.mActivity = context as AppCompatActivity
    }

    protected abstract fun initViewModel()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.initViewModel()
    }

    protected abstract fun getDataBindingConfig(): DataBindingConfig?

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val dataBindingConfig = getDataBindingConfig()!!
        val binding: ViewDataBinding =
            DataBindingUtil.inflate(inflater, dataBindingConfig.getLayout(), container, false)
        binding.lifecycleOwner = this.viewLifecycleOwner
        binding.setVariable(
            dataBindingConfig.getVmVariableId(),
            dataBindingConfig.getStateViewModel()
        )
        val bindingParams = dataBindingConfig.getBindingParams()
        var i = 0
        run {
            val length = bindingParams!!.size()
            while (i < length) {
                binding.setVariable(bindingParams.keyAt(i), bindingParams.valueAt(i))
                ++i
            }
        }

        mBinding = binding
        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding?.unbind()
        mBinding = null
    }
}